package com.bysc.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bysc.userservice.entity.AclUser;
import com.bysc.userservice.mapper.AclUserMapper;
import com.bysc.userservice.service.AclUserService;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.utils.MD5;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kkk
 * @since 2024-06-06
 */
@Service
public class AclUserServiceImpl extends ServiceImpl<AclUserMapper, AclUser> implements AclUserService {

    @Override
    public String login(AclUser aclUser) {
        String user = aclUser.getUser();
        String password = aclUser.getPassword();
//校验参数
        if (StringUtils.isEmpty(user) || StringUtils.isEmpty(password)) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.VALIDATEUSER_ERROR);
        }
//获取管理员
        AclUser member = baseMapper.selectOne(new QueryWrapper<AclUser>().eq("user", user));
        if (null == member) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.VALIDATEUSER_ERROR);
        }
//校验密码
        if (!MD5.encrypt(password).equals(member.getPassword())) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.VALIDATEPWD_ERROR);
        }
//使用JWT生成token字符串
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname(),member.getClubId());
        member.setToken(token);
        baseMapper.updateById(member);
        return token;
    }
}
